package com.uuah.server.config.spring.factories;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;

import com.uuah.api.lifecycle.Initialisable;
import com.uuah.exception.lifecycle.InitialisationException;
import com.uuah.server.api.context.IUuahContextAware;
import com.uuah.server.api.endpoint.IUuahEndpoint;
import com.uuah.server.endpoint.EndpointURIEndpointBuilder;


public class EndpointFactoryBean extends EndpointURIEndpointBuilder implements
		FactoryBean, IUuahContextAware, Initialisable {
	protected transient final Logger logger = LoggerFactory.getLogger(getClass());

	public static final String ENDPOINT_TYPE_SENDER = "sender";
	public static final String ENDPOINT_TYPE_RECEIVER = "receiver";

	public static final String ALWAYS_CREATE_STRING = "ALWAYS_CREATE";
	public static final String NEVER_CREATE_STRING = "NEVER_CREATE";

	private String type;

	public EndpointFactoryBean() {
		super();
	}

	public Object getObject() throws Exception {
		if (ENDPOINT_TYPE_RECEIVER.equals(type)) {
			if (logger.isDebugEnabled()) {
				logger
						.debug("Endpont type is \"receiver\", building request endpoint");
			}
			return uuahContext.getRegistry().lookupEndpointFactory()
					.getRequestEndpoint(this);
		} else if (ENDPOINT_TYPE_SENDER.equals(type)) {
			if (logger.isDebugEnabled()) {
				logger
						.debug("Endpont type is \"sender\", building request endpoint");
			}
			return uuahContext.getRegistry().lookupEndpointFactory()
					.getRequestEndpoint(this);
		} else {
			throw new IllegalArgumentException("The endpoint type: " + type
					+ "is not recognized.");
		}
	}

	public Class getObjectType() {
		return IUuahEndpoint.class;
	}

	public boolean isSingleton() {
		return true;
	}

	public void initialise() throws InitialisationException {
		// nothing to do, subclasses may override
	}

	public void setType(String type) {
		this.type = type;
	}

}
